import {
  defineComponent,
  onMounted,
  ref,
  computed,
  watch,
} from 'vue';
// import { useQuasar } from '@teld/q-components';
import useMappingProps from 't/common/hooks/useMappingProps';
import { commonProps, createNameSpace } from 't/common/utils';

import { showImagePreview, ImagePreview as VanImagePreview } from 'vant';
import 'vant/lib/image-preview/style'; // 仅引入 ImagePreview 组件的样式

import './index.scss';

export default defineComponent({
  name: createNameSpace('ImagePreview'),
  props: {
    ...commonProps,
    /** v-mode 用，类型`Boolean | String | null | undefined` */
    modelValue: {
      default: null,
    },
    srcList: {
      type: Array,
      default: () => [],
    },
  },
  emits: ['update:model-value'],
  setup(props, { emit }) {
    // const $q = useQuasar();
    const tmImgPreviewRef = ref();
    const [mappingProps, mappingExpose] = useMappingProps(props);

    const total = computed(() => mappingProps.srcList.length);

    /**
     * @summary 初始化图片索引
     * @returns 当前图片索引
     * @description
     * - 图片列表为空时，返回 -1
     * - 如果未单独指定图片地址，返回 -1
     * - 如果指定的图片不在列表中，返回 -1
     * - 否则，返回指定图片在列表中的索引
     */
    const initIndex = () => {
      if (total.value < 1 || !props.modelValue) return -1;
      return props.srcList.findIndex(v => v === props.modelValue);
    };
    const currentIndex = ref(initIndex());

    /**
     * 图片预览器是否可见
     * 用计算属性实现对入参的双向绑定
     */
    const vModelValue = computed({
      get() {
        return typeof props.modelValue === 'string' && props.modelValue;
      },
      set(v) {
        emit('update:model-value', v);
      },
    });

    const isImgList = computed(() => {
      return total.value && currentIndex.value !== -1;
    });

    watch(
      () => props.modelValue,
      v => {
        currentIndex.value = initIndex();
        // 延时为了放到指定容器，容器设有自定义背景底色
        setTimeout(() => {
          showImagePreview({
            images: isImgList.value
              ? mappingProps.srcList
              : vModelValue.value
                ? [vModelValue.value]
                : [],
            startPosition: currentIndex.value === -1 ? 0 : currentIndex.value,
            onClose() {
              vModelValue.value = null;
            },
            teleport: tmImgPreviewRef.value,
          });
        }, 100);
      },
      { immediate: true },
    );

    return () => {
      return (
        <div
          ref={tmImgPreviewRef}
          class='t-image-preview platform-mobile'
        ></div>
      );
    };
  },
});
